VuePress 的 iframe 自适应方案

MuYan2021-11-09VuePressVueVuePress
  • VuePress 直接在 md 文件内使用 iframe 引入其他平台视频时未能自适应 iframe 高度问题。

直接使用:

<iframe
  width="100%"
  frameborder="no"
  scrolling="no"
  seamless=""
  allowfullscreen="allowfullscreen"
  src="url地址"
></iframe>

效果:

  • 解决办法通过自定义组件解决该问题
<!-- .vuepress/components/mIframe.vue-->
<template>
  <iframe
    class="m-iframe"
    width="100%"
    frameborder="no"
    scrolling="no"
    seamless=""
    allowfullscreen="allowfullscreen"
    :src="src"
    v-if="src"
  ></iframe>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      default: "",
    },
  },
  mounted() {
    this.initIframe();
    window.onresize = () => {
      this.initIframe();
    };
  },
  methods: {
    initIframe() {
      const iframeList = document.getElementsByClassName("m-iframe");
      if (!iframeList.length) return;
      const width = document.getElementsByClassName("m-iframe")[0].scrollWidth;
      for (let i = 0; i < iframeList.length; i++) {
        iframeList[i].style.height = `${width * 0.75}px`;
      }
    },
  },
};
</script>
  • 使用自定义组件(可直接在 md 页面内使用,无需引入)
<mIframe src="url地址"/>
  • 效果如下
上次更新 2026/6/23 11:49:15
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8